<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, User,Upload } from '@element-plus/icons-vue'

// 系统设置表单数据
const systemForm = reactive({
  systemName: '个人简历管理系统',
  systemLogo: 'https://example.com/logo.png',
  systemDesc: '一个功能完善的个人简历管理平台',
  copyright: '© 2023 简历管理系统',
  recordNumber: '粤ICP备XXXXXXXX号',
  contactEmail: 'admin@example.com'
})

// 用户账号表单数据
const accountForm = reactive({
  username: 'admin',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  avatar: 'https://example.com/avatar.jpg'
})

// 数据库设置表单数据
const databaseForm = reactive({
  dbType: 'MySQL',
  dbHost: 'localhost',
  dbPort: '3306',
  dbName: 'resume_db',
  dbUsername: 'root',
  dbPassword: '******',
  backupPath: '/backup',
  autoBackup: true,
  backupInterval: 7 // 天
})

// 表单验证规则
const systemRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const accountRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== accountForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const databaseRules = {
  dbHost: [{ required: true, message: '请输入数据库主机地址', trigger: 'blur' }],
  dbPort: [{ required: true, message: '请输入数据库端口', trigger: 'blur' }],
  dbName: [{ required: true, message: '请输入数据库名称', trigger: 'blur' }],
  dbUsername: [{ required: true, message: '请输入数据库用户名', trigger: 'blur' }]
}

// 表单引用
const systemFormRef = ref()
const accountFormRef = ref()
const databaseFormRef = ref()

// 保存系统设置
const saveSystemSettings = async () => {
  if (!systemFormRef.value) return
  
  await systemFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API保存系统设置
      // await saveSystemSettingsAPI(systemForm)
      ElMessage.success('系统设置保存成功')
    } else {
      return false
    }
  })
}

// 保存账号设置
const saveAccountSettings = async () => {
  if (!accountFormRef.value) return
  
  await accountFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API保存账号设置
      // await updatePasswordAPI(accountForm)
      ElMessage.success('账号设置保存成功')
      // 重置密码字段
      accountForm.oldPassword = ''
      accountForm.newPassword = ''
      accountForm.confirmPassword = ''
    } else {
      return false
    }
  })
}

// 保存数据库设置
const saveDatabaseSettings = async () => {
  if (!databaseFormRef.value) return
  
  await databaseFormRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        '修改数据库配置可能导致系统不稳定，确定要保存吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 这里应该调用API保存数据库设置
        // await saveDatabaseSettingsAPI(databaseForm)
        ElMessage.success('数据库设置保存成功')
      }).catch(() => {
        ElMessage.info('已取消保存')
      })
    } else {
      return false
    }
  })
}

// 上传Logo处理函数
const handleLogoUpload = (file) => {
  // 这里应该调用上传API
  // const formData = new FormData()
  // formData.append('file', file)
  // const res = await uploadAPI(formData)
  // systemForm.systemLogo = res.data.url
  
  // 模拟上传成功
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    systemForm.systemLogo = reader.result
    ElMessage.success('Logo上传成功')
  }
  return false // 阻止默认上传行为
}

// 上传头像处理函数
const handleAvatarUpload = (file) => {
  // 这里应该调用上传API
  // const formData = new FormData()
  // formData.append('file', file)
  // const res = await uploadAPI(formData)
  // accountForm.avatar = res.data.url
  
  // 模拟上传成功
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    accountForm.avatar = reader.result
    ElMessage.success('头像上传成功')
  }
  return false // 阻止默认上传行为
}

// 数据库备份
const backupDatabase = () => {
  ElMessageBox.confirm(
    '确定要立即备份数据库吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 这里应该调用备份API
    // await backupDatabaseAPI()
    ElMessage.success('数据库备份成功')
  }).catch(() => {
    ElMessage.info('已取消备份')
  })
}

// 数据库恢复
const restoreDatabase = () => {
  ElMessageBox.confirm(
    '恢复数据库将覆盖当前数据，确定要继续吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里应该调用恢复API
    // await restoreDatabaseAPI()
    ElMessage.success('数据库恢复成功')
  }).catch(() => {
    ElMessage.info('已取消恢复')
  })
}
</script>

<template>
  <div class="setting-container">
    <div class="setting-header">
      <h2 class="setting-title">系统设置</h2>
      <p class="setting-subtitle">管理系统基本信息、账号和数据库配置</p>
    </div>
    
    <!-- 系统基本设置 -->
    <el-card class="setting-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Setting /></el-icon>
          <span>系统基本设置</span>
        </div>
      </template>
      
      <el-form
        ref="systemFormRef"
        :model="systemForm"
        :rules="systemRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="systemForm.systemName" placeholder="请输入系统名称" />
        </el-form-item>
        
        <el-form-item label="系统Logo">
          <div class="logo-upload">
            <el-image 
              v-if="systemForm.systemLogo" 
              :src="systemForm.systemLogo" 
              class="logo-image" 
              fit="contain"
            />
            <el-upload
              class="upload-btn"
              action="#"
              :http-request="handleLogoUpload"
              :show-file-list="false"
              accept="image/jpeg,image/png,image/gif"
            >
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                上传Logo
              </el-button>
            </el-upload>
          </div>
          <div class="form-tip">建议上传尺寸: 200px × 60px，支持JPG、PNG格式</div>
        </el-form-item>
        
        <el-form-item label="系统描述">
          <el-input 
            v-model="systemForm.systemDesc" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入系统描述"
          />
        </el-form-item>
        
        <el-form-item label="版权信息">
          <el-input v-model="systemForm.copyright" placeholder="请输入版权信息" />
        </el-form-item>
        
        <el-form-item label="备案号">
          <el-input v-model="systemForm.recordNumber" placeholder="请输入备案号" />
        </el-form-item>
        
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="systemForm.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveSystemSettings">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 账号设置 -->
    <el-card class="setting-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><User /></el-icon>
          <span>账号设置</span>
        </div>
      </template>
      
      <el-form
        ref="accountFormRef"
        :model="accountForm"
        :rules="accountRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="用户名">
          <el-input v-model="accountForm.username" disabled />
          <div class="form-tip">用户名不可修改</div>
        </el-form-item>
        
        <el-form-item label="头像">
          <div class="avatar-upload">
            <el-avatar 
              v-if="accountForm.avatar" 
              :src="accountForm.avatar" 
              :size="100" 
              class="avatar-image"
            />
            <el-upload
              class="upload-btn"
              action="#"
              :http-request="handleAvatarUpload"
              :show-file-list="false"
              accept="image/jpeg,image/png,image/gif"
            >
              <el-button type="primary">
                <el-icon><Upload /></el-icon>
                上传头像
              </el-button>
            </el-upload>
          </div>
          <div class="form-tip">建议上传尺寸: 200px × 200px，支持JPG、PNG格式</div>
        </el-form-item>
        
        <el-divider content-position="left">修改密码</el-divider>
        
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="accountForm.oldPassword" 
            type="password" 
            placeholder="请输入原密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="accountForm.newPassword" 
            type="password" 
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="accountForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码" 
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveAccountSettings">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据库设置 -->
    <el-card class="setting-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><DataBase /></el-icon>
          <span>数据库设置</span>
        </div>
      </template>
      
      <el-form
        ref="databaseFormRef"
        :model="databaseForm"
        :rules="databaseRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="数据库类型">
          <el-select v-model="databaseForm.dbType" placeholder="请选择数据库类型">
            <el-option label="MySQL" value="MySQL" />
            <el-option label="PostgreSQL" value="PostgreSQL" />
            <el-option label="SQLite" value="SQLite" />
            <el-option label="MongoDB" value="MongoDB" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="数据库主机" prop="dbHost">
          <el-input v-model="databaseForm.dbHost" placeholder="请输入数据库主机地址" />
        </el-form-item>
        
        <el-form-item label="数据库端口" prop="dbPort">
          <el-input v-model="databaseForm.dbPort" placeholder="请输入数据库端口" />
        </el-form-item>
        
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="databaseForm.dbName" placeholder="请输入数据库名称" />
        </el-form-item>
        
        <el-form-item label="数据库用户名" prop="dbUsername">
          <el-input v-model="databaseForm.dbUsername" placeholder="请输入数据库用户名" />
        </el-form-item>
        
        <el-form-item label="数据库密码">
          <el-input 
            v-model="databaseForm.dbPassword" 
            type="password" 
            placeholder="请输入数据库密码" 
            show-password
          />
        </el-form-item>
        
        <el-divider content-position="left">备份设置</el-divider>
        
        <el-form-item label="备份路径">
          <el-input v-model="databaseForm.backupPath" placeholder="请输入备份路径" />
        </el-form-item>
        
        <el-form-item label="自动备份">
          <el-switch v-model="databaseForm.autoBackup" />
        </el-form-item>
        
        <el-form-item label="备份间隔" v-if="databaseForm.autoBackup">
          <el-input-number 
            v-model="databaseForm.backupInterval" 
            :min="1" 
            :max="30"
          />
          <span class="input-suffix">天</span>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveDatabaseSettings">保存设置</el-button>
          <el-button type="success" @click="backupDatabase">立即备份</el-button>
          <el-button type="warning" @click="restoreDatabase">恢复数据库</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.setting-container {
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  border-radius: 8px;
}

.setting-header {
  margin-bottom: 30px;
  text-align: center;
  position: relative;
  padding-bottom: 15px;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 80px;
    height: 3px;
    background: linear-gradient(90deg, #409eff, #67c23a);
    border-radius: 3px;
  }
}

.setting-title {
  margin-bottom: 10px;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  letter-spacing: 1px;
}

.setting-subtitle {
  font-size: 16px;
  color: #909399;
  margin-bottom: 0;
}

.setting-card {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
  }
  
  .card-header {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    padding: 15px 20px;
    background: linear-gradient(to right, #f8f9fa, #ffffff);
    
    .el-icon {
      margin-right: 10px;
      font-size: 22px;
      color: #409eff;
      background: rgba(64, 158, 255, 0.1);
      padding: 8px;
      border-radius: 8px;
    }
  }
  
  :deep(.el-card__body) {
    padding: 25px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
  
  :deep(.el-button) {
    padding: 12px 20px;
    border-radius: 6px;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }
}

.logo-upload, .avatar-upload {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  
  .logo-image {
    width: 200px;
    height: 60px;
    margin-right: 25px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 5px;
    background-color: white;
  }
  
  .avatar-image {
    margin-right: 25px;
    border: 2px solid #ebeef5;
    border-radius: 50%;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.05);
    }
  }
  
  .upload-btn {
    display: inline-block;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
  padding-left: 5px;
  border-left: 2px solid #dcdfe6;
}

.input-suffix {
  margin-left: 10px;
  color: #606266;
  font-weight: 500;
}

.el-divider__text {
  font-size: 16px;
  font-weight: bold;
  color: #606266;
  background: linear-gradient(to right, #f0f2f5, #ffffff, #f0f2f5);
  padding: 0 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
  .el-input__wrapper {
    border-radius: 6px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;
    
    &:hover, &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
}
</style>